<template>
  <div>
    <div class="shoppingCart">
      <div class="shopsBox" :style="boxStyle">
        <div class="banner">
          <div class="content">
            <div @click="goBack"><span class="el-icon-arrow-left"></span>返回</div>
            <div>我的购物车</div>
            <div>温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算</div>
          </div>
        </div>
        <hr>
        <div class="shopsList">
          <div class="shoppingBar">
            <h2>购物清单</h2>
            <SearchBar @del="del" @refresh="refresh"/>
            <tableList 
              :columns="tableCols"
              :data="tableData"
              :operates="operates"
              :isOperates="false"
              :enableEdit="true"
              ref="list"
              :isSelection="true"
              @handleSelect="handleSelect" />
              <pagination :pageData="pageList" @change="pageChange" />
              <div class="buy">
                <div class="toPay" @click="pay">去付款</div>
                <div>共 <span style="color:red">{{payInfo.nums}}</span> 件商品，总计 <span style="color: red;font-weight: bold;font-size: 18px;">{{payInfo.money}}</span> 元</div>
              </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import tableList from "@/components/index/tableList";
import SearchBar from "@/components/index/SearchBar";
import pagination from "@/components/index/pagination";
import { findGoodsCar,updateGoodsCarNums,deleteGoodsCar,deleteGoodsCars } from "@/js/api/home"; // 
export default {
  name:'shoppingCart',
  components:{
    tableList,
    SearchBar,
    pagination,
  },
  data(){
    return {
      boxStyle:{},
      tableCols: [
        { label: "商品名称", prop: "goods_name",sortable: true,edit:false },
        { label: "数量", prop: "nums",minWidth:'100px',width:'150px',minlength:1, sortable: true, type:'number',edit:true,
          method:(obj,val)=>{
            if(val>=1){
              let prams = {
                carId:new String(obj.carId),
                userId:window.localStorage.userId,
                nums:new String(val)
              }
              updateGoodsCarNums(prams).then()
            }
          } 
        },
        { label: "单价（元）", prop: "goods_price",edit:false,
          render(h,params) {
            return h('span',{
              domProps: {
                innerHTML : '¥'+params.row.goods_price
              }
            },params)
          }, 
        },
        { label: "金额（元）", prop: "money", sortable: true,edit:false,
          render(h,params) {
            return h('span',{
              style:{
                color:'red',
                'font-weight': 'bold',
                'font-size':'18px'
              },
              domProps: {
                innerHTML : '¥'+parseInt(params.row.nums)*parseInt(params.row.goods_price)
              }
            },params)
          }, 
        },
      ],
      tableData:[],
      operates: {
        width: 100,
        list: [
          {
            id: "1",
            label: "删除",
            type: "text",
            show: true,
            disabled: false,
            size: "small",
            method: (index, row) => {
              this.deleteData([row.id])
            },
          },
        ],
      },
      pageList:{pageSize:4,pageNo:1,total:10},
      selectRows:[],
      condition:"",
    }
  },
  computed:{
    payInfo:function(){
      let money = 0;
      for(let i of this.selectRows){
        money += parseInt(i.goods_price)*parseInt(i.nums)
      }
      let obj = {
        nums:this.selectRows.length,
        money:money
      }
      return obj
    },
  },
  mounted(){
    let body = {
      height:document.querySelector(".shoppingBar").clientHeight+150+"px"
    }
    this.boxStyle = body
  },
  created(){
    this.loadList()
  },
  methods:{
    del(){
      if(this.selectRows.length>0){
        this.utils.tips.confirm("确定要删除吗？",(val)=>{
          if(val){
            let ids = []
            for(let i of this.selectRows){
              ids.push(i.carId)
            }
            this.deleteData(ids)
          }
        })
      }
    },
    pageChange(val){
      console.log(val);
    },
    update(){
      this.loadList()
    },
    deleteData(ids){
      if(ids.length<=1){
        deleteGoodsCar(window.localStorage.userId,ids[0]).then(response=>{
          if(response.data.state){
            this.utils.tips.success(response.data.msg)
            this.loadList()
          }else{
            this.utils.tips.error(response.data.msg)
          }
        })
      }else{
        let idArr = {u:window.localStorage.userId,c:ids.join()}
        deleteGoodsCars({ids:JSON.stringify(idArr)}).then(response=>{
          if(response.data.state){
            this.utils.tips.success(response.data.msg)
            this.loadList()
          }else{
            this.utils.tips.error(response.data.msg)
          }
        })
      }
      this.$refs.list.clearSelect()
    },
    loadList(){
      let obj = {
        userId:window.localStorage.userId,
        pageNo:this.pageList.pageNo,
        pageSize:this.pageList.pageSize,
        search:JSON.stringify({goods_name:this.condition})
      }
      findGoodsCar(obj).then(response=>{
        if(response.data.state){
          this.tableData = response.data.data.list
          this.pageList.pageNo = response.data.data.pageNo
          this.pageList.pageSize = response.data.data.pageSize
          this.pageList.total = response.data.data.totalRecords
        }
      })
    },
    pay(){
      if(this.selectRows.length!=0){
        this.$router.push({path: '/shoppingConfirm',query:{obj:JSON.stringify(this.selectRows),action:2}});
      }else{
        this.utils.tips.warning("您还未选择购买哪件商品")
      }
    },
    refresh(val){
      this.condition = val
      this.loadList()
    },
    goBack(){
      this.$router.go(-1)
    },
    handleSelect(val){
      this.selectRows = val == undefined ? [] : val
    }
  },
}
</script>

<style lang="less">
.shoppingCart{
  .shopsBox{
    margin-top: 10px;
    left: 0;
    width: 100%;
    // height: 920px;
    background-color: #F5F5F5;
    @import "~@/less/banner.less";
    .shopsList{
      padding: 0 50px;
      .shoppingBar{
        position: relative;
        width: 100%;
        height: 500px;
        background-color: white;
        .is-scrolling-none{
          height: 100%;
        }
        h2{
          position: relative;
          top: 20px;
          left: 50px;
        }
        .buy{
          float: right;
          margin-top: 20px;
          div{
            margin-right: 20px;
            line-height: 50px;
            float: right;
          }
          .toPay{
            cursor: pointer;
            text-align: center;
            display: block;
            width: 152px;
            height: 50px;
            color: white;
            background-color: #f13e3a;
            overflow: hidden;
          }
        }
      }
    }
    .bottom{
      position: relative;
      top: 150px;
    }
  }
}
</style>